package com.wechat.demo.controller;

import com.wechat.demo.util.CheckUtil;
import com.wechat.demo.util.MessageUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

@RestController
public class WeChatController {

    @GetMapping(value = "/verify_wx_token")
    public String WeChatInterface(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("---------------------------验证微信服务号信息开始------------------------------");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        //微信加密签名
        String signature = request.getParameter("signature");
        //时间戳
        String timestamp = request.getParameter("timestamp");
        //随机数
        String nonce = request.getParameter("nonce");
        //随机字符串
        String echostr = request.getParameter("echostr");

        if (CheckUtil.checkSignature(signature,timestamp,nonce)){
//            System.out.println("成功");
            return echostr;
        }else {
//            System.out.println("失败");
            return null;
        }
    }

    @PostMapping(value = "/verify_wx_token")
    public void handler(HttpServletRequest request,HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        Map<String,String> parseXml = MessageUtil.parseXml(request);
        String msgType = parseXml.get("MsgType");
        String content = parseXml.get("Content");
        String fromusername = parseXml.get("FromUserName");
        String tousername = parseXml.get("ToUserName");
        System.out.println(msgType);
        System.out.println(content);
        System.out.println(fromusername);
        System.out.println(tousername);
    }

}
